package com.tengju.support.infrastructure.persistence.redis;

import com.tengju.support.domain.model.rule.Rule;
import com.tengju.support.domain.model.rule.RuleId;
import com.tengju.support.infrastructure.persistence.redis.dataobject.RedisKeyObject;
import com.tengju.support.infrastructure.persistence.redis.dataobject.RedisKeyPrefix;
import com.tengju.user.domain.shared.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

@Repository
public class RuleCacheRepository {

    @Autowired
    private RedisService redisService;


    /**
     * 获取规则
     */
    public Rule getRule(RuleId ruleId){
        RedisKeyObject redisKeyObject = new RedisKeyObject(RedisKeyPrefix.RULE,ruleId.getValue() + "");
        String ruleJson = redisService.getString(redisKeyObject);
        return JsonUtil.toObject(ruleJson,Rule.class);
    }

    /**
     * 缓存规则
     */
    public void cacheRule(Rule rule) {
        if (rule == null) {
            return;
        }
        RedisKeyObject redisKeyObject = new RedisKeyObject(RedisKeyPrefix.RULE,rule.getRuleId().getValue() + "");
        redisService.setValue(redisKeyObject, JsonUtil.toJSONString(rule),30, TimeUnit.MINUTES);
    }

    public void deleteRule(RuleId ruleId) {
        if (ruleId == null) {
            return;
        }
        RedisKeyObject redisKeyObject = new RedisKeyObject(RedisKeyPrefix.RULE,ruleId.getValue() + "");
        redisService.delKey(redisKeyObject);
    }
}
